package ink.xiaobaibai.controller.onePay;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ink.xiaobaibai.annotation.InsidePublicResources;
import ink.xiaobaibai.autoConfig.roleResources.ResourcesRoleMapping;
import ink.xiaobaibai.common.MyRole;
import ink.xiaobaibai.common.PageInfo;
import ink.xiaobaibai.entity.OxygenDevice;
import ink.xiaobaibai.entity.OzoneDevice;
import ink.xiaobaibai.enumOxy.DeviceStatus;
import ink.xiaobaibai.response.ResponseFormat;
import ink.xiaobaibai.service.IAdminUserService;
import ink.xiaobaibai.service.IOxygenDeviceService;
import ink.xiaobaibai.service.IOzoneDeviceService;
import ink.xiaobaibai.units.MySecurity;
import ink.xiaobaibai.valited.DeviceStatusValid;
import ink.xiaobaibai.valited.UpdateGroup;
import ink.xiaobaibai.vo.OrderItemInfoVo;
import ink.xiaobaibai.vo.UserByDeviceVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * @description: 氧气机控制层
 * @author: 小白白
 * @create: 2021-05-23
 **/

@RestController
@RequestMapping("/onePay/oxygenDevice")
@CrossOrigin
@Api(tags = "氧气机控制接口")
@InsidePublicResources
public class OxygenDeviceController {

    @Autowired
    private IOxygenDeviceService oxygenDeviceService;

    @Autowired
    private IOzoneDeviceService ozoneDeviceService;

    @Autowired
    private IAdminUserService adminUserService;

    /**
     * 获取氧氧机集合
     * 分页|识别码|个人|部门|故障|运行|空闲|省区
     */
    @GetMapping("/list")
    @ApiOperation("获取氧气机集合|查询条件: 分页,识别码(可选),个人(可选),部门(可选),故障机器(可选),空闲机器(可选),运行机器(可选),是哪台臭氧的负责机(填入臭氧机的识别码)(可选),个人和部门不可同时存在,识别码不可和其他参数同时存在")
    public ResponseFormat getOxygenDeviceList(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                              @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize,
                                              @RequestParam(value = "code", required = false) String code,
                                              @RequestParam(value = "adminUserId", required = false) Integer adminUserId,
                                              @RequestParam(value = "depId", required = false) Integer depId,
                                              @RequestParam(value = "provinceCity", required = false) String provinceCity,
                                              @RequestParam(value = "status", required = false) @DeviceStatusValid String status) {

        String role = MySecurity.getRole();
        Set<String> roles = MySecurity.getRoles();
        Integer userId = MySecurity.getUserId();
        if (!roles.contains(MyRole.POWER_ONE)) {
            if (role.equals(MyRole.DISTRIBUTOR)) {
                //业务员
                depId = null;
                adminUserId = userId;
            } else if (role.equals(MyRole.AGENT)) {
                //经理
                //机器码校验
                if (code != null) {
                    //不能查看其他部门的机器
                    QueryWrapper<OxygenDevice> q1 = new QueryWrapper<>();
                    q1.eq("device_code", code);
                    OxygenDevice oxygen = this.oxygenDeviceService.getOne(q1);
                    if (oxygen == null) {
                        return ResponseFormat.fail("当前机器不存在");
                    }
                    if (!this.adminUserService.identicalDep(oxygen.getAdminUserId(), userId)) {
                        return ResponseFormat.fail("不可查看其他部门机器");
                    }
                    return ResponseFormat.success(new PageInfo<>(Collections.singletonList(oxygen), 1, 1));
                }
                //部门校验
                if (depId != null && StringUtils.equals(depId.toString(), this.adminUserService.getDepId(userId).toString())) {
                    return ResponseFormat.fail("不可查看其他部门机器");
                }
                //用户校验
                if (adminUserId != null && !this.adminUserService.identicalDep(adminUserId, userId)) {
                    return ResponseFormat.fail("不可查看其他部门人员机器");
                }
            }
        }
        if (code != null) {
            //不能查看其他部门的机器
            QueryWrapper<OxygenDevice> q1 = new QueryWrapper<>();
            q1.eq("device_code", code);
            OxygenDevice oxygen = this.oxygenDeviceService.getOne(q1);
            if (oxygen == null) {
                return ResponseFormat.fail("当前机器不存在");
            }
            return ResponseFormat.success(new PageInfo<>(Collections.singletonList(oxygen), 1, 1));
        }
        //通过校验
        PageInfo<OxygenDevice> pageInfo = this.oxygenDeviceService.getOxygenDeviceList(pageNum, pageSize, adminUserId, depId, provinceCity, status);
        return ResponseFormat.success(pageInfo);
    }

    /**
     * 单体氧气机详细信息  获取当前氧气机的详细信息: 负责人名称,负责部门名称
     */
    @GetMapping("/item/{id}")
    @ApiOperation("单氧气机详细信息(机器信息+负责人信息)")
    public ResponseFormat getOxygenItem(@PathVariable("id") Integer id) {
        //机器信息
        OxygenDevice oxygenDevice = this.oxygenDeviceService.getById(id);
        //负责人信息+负责人部门
        UserByDeviceVo userByDeviceId = this.oxygenDeviceService.getUserInfoByUserId(oxygenDevice.getAdminUserId());
        return ResponseFormat.success(new OrderItemInfoVo(oxygenDevice, userByDeviceId, null));
    }

    /**
     * 增加氧气机
     */
    @PostMapping("/add")
    @ApiOperation("增加氧气机")
    @ResourcesRoleMapping(resourceName = "增加订单氧气机", includeRoleNames = {MyRole.ADMIN, MyRole.POWER_ONE})
    public ResponseFormat addOxygen(@RequestBody @Validated OxygenDevice oxygenDevice) {
        //识别码,负责人
        oxygenDevice.setId(null);
        ResponseFormat state = this.validOxygenDevice(oxygenDevice);
        if (state.getCode() == 1) {
            return state;
        }
        Integer userId = MySecurity.getUserId();
        //默认状态
        if (oxygenDevice.getAdminUserId() == null) {
            oxygenDevice.setAdminUserId(userId);
            oxygenDevice.setDepId(this.adminUserService.getDepId(userId));
        } else {
            if (!this.adminUserService.existsUser(oxygenDevice.getAdminUserId())) {
                return ResponseFormat.fail("绑定用户不存在");
            }
            oxygenDevice.setDelayedTime(this.adminUserService.getDepId(userId));
        }
        oxygenDevice.setStatus(DeviceStatus.FREE.getStatus());
        this.oxygenDeviceService.save(oxygenDevice);
        return ResponseFormat.success();
    }

    /**
     * 修改氧气机
     */
    @PutMapping("/update")
    @ApiOperation("修改氧气机")
    @ResourcesRoleMapping(resourceName = "修改定点氧气机", includeRoleNames = {MyRole.ADMIN, MyRole.POWER_ONE})
    public ResponseFormat updateOxygen(@RequestBody @Validated(value = UpdateGroup.class) OxygenDevice oxygenDevice) {
        if (oxygenDevice.getId() == null) {
            return ResponseFormat.fail("id不可为空");
        }
        //识别码,负责人
        ResponseFormat state = this.validOxygenDevice(oxygenDevice);
        if (state.getCode() == 1) {
            return state;
        }
        if (oxygenDevice.getAdminUserId() != null) {
            if (!this.adminUserService.existsUser(oxygenDevice.getAdminUserId())) {
                return ResponseFormat.fail("绑定用户不存在");
            }
            oxygenDevice.setDepId(this.adminUserService.getDepId(oxygenDevice.getAdminUserId()));
        }
        this.oxygenDeviceService.updateById(oxygenDevice);
        return ResponseFormat.success();
    }

    /**
     * 修改氧气机状态
     */
    @PutMapping("/update-status")
    @ApiOperation("修改氧气机状态,如果当前状态为停运,那么对应的臭氧机都得停运")
    @ResourcesRoleMapping(resourceName = "修改定点氧气机状态", includeRoleNames = {MyRole.ADMIN, MyRole.POWER_ONE})
    public ResponseFormat updateOxygenStatus(@RequestParam("deviceId") Integer deviceId,
                                             @RequestParam("status") @DeviceStatusValid String status) {
        /**
         * 正常(无操作) 停运(子机器全停运) 故障(子机器全故障)
         */
        /**
         * 故障状态: 应该是终端改变,不可人为改变
         * 氧气机没有掉线状态 它的掉线状态的症状就是对应所有臭氧机掉线
         */
        DeviceStatus deviceStatus = DeviceStatus.valueOf(status.toUpperCase());
        if (deviceStatus == DeviceStatus.STOP) {
            //停运,close所有臭氧机,两机改状态
            this.oxygenDeviceService.updateDeviceStatus(deviceId, DeviceStatus.STOP);
        } else if (deviceStatus == DeviceStatus.FREE) {
            //修复为正常状态
            this.oxygenDeviceService.updateDeviceStatus(deviceId, DeviceStatus.FREE);
        } else {
            return ResponseFormat.fail("不可修改为当前状态");
        }
        return ResponseFormat.success();
    }

    /**
     * 删除氧气机
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除氧气机")
    @ResourcesRoleMapping(resourceName = "删除定点氧气机", includeRoleNames = {MyRole.ADMIN, MyRole.POWER_ONE})
    public ResponseFormat deleteOxygenDevice(@PathVariable("id") Integer id) {
        QueryWrapper<OzoneDevice> q1 = new QueryWrapper<>();
        q1.eq("oxygen_id", id);
        int count = this.ozoneDeviceService.count(q1);
        if (count != 0) {
            return ResponseFormat.fail("还有对应的臭氧机依赖,不可删除");
        }
        this.oxygenDeviceService.removeById(id);
        return ResponseFormat.success();
    }

    /**
     * 当前氧气机绑定的臭氧机们
     */
    @GetMapping("/getOzoneDeviceList/{id}")
    @ApiOperation("当前氧气机绑定的臭氧机们")
    public ResponseFormat getOzoneDeviceListByOxygenId(@PathVariable("id") Integer id) {
        QueryWrapper<OzoneDevice> q1 = new QueryWrapper<>();
        q1.eq("oxygen_id", id);
        List<OzoneDevice> list = this.ozoneDeviceService.list(q1);
        return ResponseFormat.success(list);
    }

    private ResponseFormat validOxygenDevice(OxygenDevice oxygenDevice) {
        String deviceCode = oxygenDevice.getDeviceCode();
        QueryWrapper<OxygenDevice> q2 = new QueryWrapper<>();
        q2.select("id", "device_code");
        q2.eq("device_code", deviceCode);
        q2.last("limit 1");
        OxygenDevice dbOxygen = this.oxygenDeviceService.getOne(q2);
        //增加时
        if (oxygenDevice.getId() == null && dbOxygen != null) {
            return ResponseFormat.fail("机器码重复");
        }
        //修改时
        if (oxygenDevice.getId() != null && dbOxygen != null && !oxygenDevice.getId().equals(dbOxygen.getId())) {
            return ResponseFormat.fail("机器码重复");
        }
        return ResponseFormat.success();
    }

}
